package com.zhentao.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.zhentao.common.Constans;
import com.zhentao.dto.UserDto;
import com.zhentao.redis.CacheService;
import com.zhentao.user.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName: LoginInterceptor
 * @Author: 振涛教育_Q
 * @Date: 2024/11/18 9:21
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;
    public RefreshTokenInterceptor( StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("authorization");
//        System.err.println(token);
        if (token != null) {
            String key = Constans.USER_LOGIN_REDIS + token;
            // 获取redis中用户信息
            Map<Object, Object> user = redisTemplate.opsForHash().entries(key);
            if (StringUtils.isEmpty(user)) {
                return true;
            }
            // hash转换为DTO  第三个参数如果在填充的过程中出现不匹配，则抛出异常
            UserDto userDTO = BeanUtil.fillBeanWithMap(user, new UserDto(), false);
            // 保存在threadlocal
            UserHolder.saveUser(userDTO);
            // 刷新有效时间
            redisTemplate.expire(key
                    , Constans.USER_REDIS_EXPIRE, java.util.concurrent.TimeUnit.MINUTES);
            // 放行
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
